package at.ac.tuwien.prog.view;

import javax.swing.table.AbstractTableModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import at.ac.tuwien.prog.entity.Register;
import at.ac.tuwien.prog.memory.IDisplayDataListener;
import at.ac.tuwien.prog.memory.IMemoryManager;
import at.ac.tuwien.prog.memory.MemoryConstants;

/**
 * 
 * @author christoph.pickl@student.tuwien.ac.at
 */
public class DataTableModel extends AbstractTableModel implements IDisplayDataListener {
	
	private static final Log LOG = LogFactory.getLog(DataTableModel.class);

	private static final long serialVersionUID = 39149390027265422L;

	private final IMemoryManager memory;
	
	public DataTableModel(IMemoryManager memory) {
		this.memory = memory;
		
		this.fireTableDataChanged();
		
		this.memory.addDisplayDataListener(this);
	}
	
	public int getColumnCount() {
		return 32;
	}

	public int getRowCount() {
		return 4;
	}

	public Object getValueAt(int rowIndex, int columnIndex) {
		final Register registerValue = this.memory.getRegisterValue(convertRowColToAddress(rowIndex, columnIndex));
		return (char) registerValue.getIntValue();
	}

	public void dataChanged(int address, Register value) {
		LOG.debug("dataChanged");
		// final int[] rowCol = convertAddressToRowCol(address);
		//ystem.out.println("data changed: (address="+address+") rowCol="+rowCol[0]+"/"+rowCol[1]);
		//this.setValueAt(String.valueOf(value.getIntValue()), rowCol[0], rowCol[1]);
		
		this.fireTableDataChanged();
	}
	
//	private static int[] convertAddressToRowCol(int address) {
//		address -= MemoryConstants.DISPLAY_DATA_START;
//		final int row = (int) Math.floor(address / 32);
//		final int col = address % 32;
//		
//		return new int[] { row, col };
//	}
	
	private static int convertRowColToAddress(int row, int col) {
		return MemoryConstants.DISPLAY_DATA_START + (row * 32) + col; 
	}

}
